﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Linq;
using UMC.Wiki.Entities;
using UMC.Web;

namespace UMC.Wiki.Activities
{
    class SubjectNewsActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var user = this.Context.Token.Identity();
            if (user.IsAuthenticated == false)
            {
                this.Prompt("请先登录", false);
                this.Context.Send("Login", true);
            }
            var sId = this.AsyncDialog("Id", r =>
            {

                var userCode = Utility.UInt64Parse(user.Id.Value);
                var projts = DataFactory.Instance().ProjectMember(user.Id.Value);
                if (projts.Length == 0)
                {
                    // var project_id = Utility.UInt64Parse(this.AsyncDialog("project_id", Utility.NewId().ToString()));

                    this.AsyncDialog("Image", "System", "Image", new WebMeta("media_id", "https://res.apiumc.com/css/icon200.jpg").Put("id", userCode), true);
                    SubjectNavActivity.Dashboard(userCode, user, out var PortfolioId);
                    return this.DialogValue(PortfolioId.ToString());
                    // return team;
                }

                var pm = projts.FirstOrDefault(d => d.project_id == userCode) ?? projts.OrderByDescending(r => r.AuthType).First();

                var pro = DataFactory.Instance().ProjectItem(new Project { Id = pm.project_id })[0];
                return this.DialogValue(DataFactory.Instance().Portfolio(pro)[0].Id.ToString());
            });

            var sub = new Subject()
            {
                CreationTime = DateTime.Now,
                Title = DateTime.Now.ToShortDateString(),
                IsPicture = false,
                Id = UMC.Data.Utility.NewId(),
                LastDate = DateTime.Now,
                Poster = user.Alias,
                Seq = UMC.Data.Utility.TimeID(),
                ReleaseTime = DateTime.Now,
                last_user_id = user.Id,
                user_id = user.Id,
                Status = -1
            };
            var portfolioId = UMC.Data.Utility.UInt64Parse(sId, 0);
            if (portfolioId > 0)
            {
                var portfolio = DataFactory.Instance().Portfolio(portfolioId);
                var projectItem = DataFactory.Instance().ProjectItem(portfolio.project_item_id.Value);
                var project = DataFactory.Instance().Project(portfolio.project_id.Value);
                var member = DataFactory.Instance().ProjectMember(project.Id.Value, user.Id.Value);

                if (member != null)
                {
                    switch (member.AuthType)
                    {
                        case WebAuthType.Admin:
                        case WebAuthType.User:
                            break;
                        default:
                            this.Prompt("提示", "您未有新增文档的权限");
                            break;
                    }

                }
                else
                {
                    this.Prompt("提示", "您未有新增文档的权限");
                }

                sub.portfolio_id = portfolioId;
                sub.project_id = project.Id;
                sub.project_item_id = projectItem.Id;

                DataFactory.Instance().Put(new Project { Id = project.Id, SubjectTotal = (project.SubjectTotal ?? 0) + 1 });

                DataFactory.Instance().Put(new ProjectDynamic
                {
                    Time = UMC.Data.Utility.TimeSpan(sub.LastDate.Value),
                    user_id = user.Id,
                    Explain = "创建了文档",
                    project_id = sub.project_id,
                    refer_id = sub.Id,
                    Title = sub.Title,
                    Alias = user.Alias,
                    Type = DynamicType.Subject
                });

                var ax = DataFactory.Instance().Attention(user.Id.Value) ?? new Attention { Id = user.Id };
                DataFactory.Instance().Put(new Attention
                {
                    Id = user.Id,
                    SubjectTotal = (ax.SubjectTotal ?? 0) + 1
                });
                DataFactory.Instance().Put(new Project
                {
                    Id = project.Id,
                    SubjectTotal = (project.SubjectTotal ?? 0) + 1
                });
                DataFactory.Instance().Put(new ProjectItem
                {
                    Id = projectItem.Id,
                    SubjectTotal = (projectItem.SubjectTotal ?? 0) + 1
                });
                DataFactory.Instance().Put(new Portfolio
                {
                    Id = project.Id,
                    SubjectTotal = (portfolio.SubjectTotal ?? 0) + 1
                });
                sub.Code = UMC.Data.Utility.Parse36Encode(Utility.IntParse(sub.Id.Value)[1]);
                DataFactory.Instance().Put(sub);
                if (request.IsApp)
                {
                    var Type = this.AsyncDialog("Type", "html/text");

                    if (String.Equals("markdown", Type, StringComparison.CurrentCultureIgnoreCase))
                    {
                        DataFactory.Instance().Put(new SubjectContent() { Id = sub.Id, ContentType = "Markdown" });
                    }
                    response.Redirect(request.Model, "Content", sub.Id.ToString());
                }
                else
                {
                    var path = String.Format("{0}/{1}/{2}", project.Code, projectItem.Code, sub.Code);
                    this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.Portfolio.New").Put("Id", portfolio.Id).Put("Sub", sub.Id).Put("Title", sub.Title)
                        .Put("Path", path), true);
                }
            }


        }

    }
}